package xyz.hubery.event;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MimeTypeUtils;
import xyz.hubery.dto.MarketDto;
import xyz.hubery.dto.TradeDTO;
import xyz.hubery.feign.MarketServiceFeign;
import xyz.hubery.model.MessagePayload;
import xyz.hubery.stream.Source;

import java.util.List;

/**
 * 成交记录事件
 */
@Component
@Slf4j
public class TradeEvent implements Event {

    @Autowired
    private MarketServiceFeign marketServiceFeign;

    /**
     * 成交记录频道
     */
    private static final String TRADE_CHANNEL = "market.%s.trade.detail";


    @Autowired
    private Source source;

    @Override
    public void handle() {
        // 获取所有的市场
        List<MarketDto> markets = marketServiceFeign.findAllMarkets();
        if(CollectionUtils.isEmpty(markets)) {
            return;
        }
        for (MarketDto market : markets) {
            // 获取该市场的所有交易记录
            List<TradeDTO> tradeDTOS = marketServiceFeign.getAllTradesById(market.getId());
            // 构建消息
            MessagePayload payload = new MessagePayload();
            payload.setChannel(String.format(TRADE_CHANNEL,market.getSymbol().toLowerCase()));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",tradeDTOS);
            payload.setBody(jsonObject.toJSONString());

            String ss = jsonObject.toString();
            log.warn("TradeEvent 消息内容大小：{}",ss.getBytes().length);

            // 发布事件
            Message<MessagePayload> message = MessageBuilder.withPayload(payload).setHeader(MessageHeaders.CONTENT_TYPE,
                    MimeTypeUtils.APPLICATION_JSON).build();
            source.subscribeEventOutput().send(message);

        }
    }
}